import json
import pathlib
import subprocess

from kivy.logger import Logger


def ffprobe_info(file_name):
    path = pathlib.Path(file_name)
    if path.is_file():
        # ffprobe -v quiet -print_format json -show_streams
        try:
            command = [r'bin\ffprobe.exe', '-v', 'quiet', '-print_format', 'json', '-show_streams',
                       f'{str(path.resolve())}']

            output = subprocess.check_output(command, creationflags=0x08000000).decode('utf-8')
            info = json.loads(output)
        except Exception as e:
            _ = e
            Logger.warning(f'ffprobe exception {file_name}')
        else:
            return info


def get_music_length(file_name):
    info = ffprobe_info(file_name)
    if info and 'streams' in info and info['streams'] and isinstance(info['streams'], list):
        return float(info['streams'][0].get('duration', 0))
    return 0
